package com.seeyon.apps.kk.listener;

import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.dao.DataAccessException;

import com.google.common.collect.Lists;
import com.seeyon.apps.collaboration.event.CollaborationAutoSkipEvent;
import com.seeyon.apps.collaboration.event.CollaborationProcessEvent;
import com.seeyon.apps.collaboration.event.CollaborationStartEvent;
import com.seeyon.apps.collaboration.event.CollaborationStopEvent;
import com.seeyon.apps.collaboration.po.ColSummary;
import com.seeyon.cap4.form.bean.FormBean;
import com.seeyon.cap4.form.bean.FormDataMasterBean;
import com.seeyon.cap4.form.bean.FormFieldBean;
import com.seeyon.ctp.common.constants.ApplicationCategoryEnum;
import com.seeyon.ctp.common.exceptions.BusinessException;
import com.seeyon.ctp.common.filemanager.Constants.ATTACHMENT_TYPE;
import com.seeyon.ctp.common.filemanager.dao.AttachmentDAO;
import com.seeyon.ctp.common.filemanager.manager.FileManager;
import com.seeyon.ctp.common.po.affair.CtpAffair;
import com.seeyon.ctp.common.po.filemanager.Attachment;
import com.seeyon.ctp.common.po.filemanager.V3XFile;
import com.seeyon.ctp.common.po.template.CtpTemplate;
import com.seeyon.ctp.organization.bo.V3xOrgMember;
import com.seeyon.ctp.organization.manager.OrgManager;
import com.seeyon.ctp.util.UUIDLong;
import com.seeyon.ctp.util.annotation.ListenEvent;
import com.seeyon.kk.utils.CAP4FormKitUtils;
import com.seeyon.kk.utils.ValueUtils;

/**
 * 其它类型单据的审批 规范 固定审批1--9
 * 
 * @author Administrator
 *
 */
public class MemberTongListtener extends BaseListener {

	private final Log log = LogFactory.getLog(MemberTongListtener.class);

	private AttachmentDAO attachmentDAO;
	private FileManager fileManager;
	private OrgManager orgManager;

	public AttachmentDAO getAttachmentDAO() {
		return attachmentDAO;
	}

	public void setAttachmentDAO(AttachmentDAO attachmentDAO) {
		this.attachmentDAO = attachmentDAO;
	}

	public FileManager getFileManager() {
		return fileManager;
	}

	public void setFileManager(FileManager fileManager) {
		this.fileManager = fileManager;
	}

	public OrgManager getOrgManager() {
		return orgManager;
	}

	public void setOrgManager(OrgManager orgManager) {
		this.orgManager = orgManager;
	}

	//@ListenEvent(event = CollaborationStopEvent.class, async = true)
	public void onStop(CollaborationStopEvent event) {
		try {
			Thread.sleep(BaseListener.LISTENER_THREAD_SLEEPTIME);
			String templetSubject = ValueUtils.getConfig().getString("kk.MemberShenPiFenPeiListtener");
			String[] templetSubjects = StringUtils.split(templetSubject, ",");
			ColSummary summary = this.colManager.getColSummaryById(event.getSummaryId()); // 获取协同信息
			CtpTemplate template = this.templateManager.getCtpTemplate(summary.getTempleteId());
			FormBean formBean = this.formManager.getFormByFormCode(template);

			if (ArrayUtils.contains(templetSubjects, template.getTempleteNumber())) {
				FormDataMasterBean formMasterBean = this.formManager.getDataMasterBeanById(summary.getFormRecordid(),
						formBean, null);
				Map<String, Object> formdata = formMasterBean.getAllDataMap();

				CtpAffair affair = event.getAffair();

				// 抄送人
				FormFieldBean csTFfb = formMasterBean.getFormTable().getFieldBeanByDisplay("抄送-填写");
				if (csTFfb != null) {
					String csTMembers = MapUtils.getString(formdata, csTFfb.getName());
					FormFieldBean csXFfb = formMasterBean.getFormTable().getFieldBeanByDisplay("抄送-显示");
					if (csTMembers != null) {
						String csXMembers = MapUtils.getString(formdata, csXFfb.getName()) + "," + csTMembers;
						CAP4FormKitUtils.setCellValue(formMasterBean, "抄送-显示", csXMembers);
						CAP4FormKitUtils.setCellValue(formMasterBean, "抄送-填写", null);
					}
				}
				CAP4FormKitUtils.setCellValue(formMasterBean, "抄送-填写", null);
				Boolean needSave = false;

				// 这里需要根据用户 获取到个性化的签名，如果没有 则使用默认的
				Long defaultNoImageId = ValueUtils.getConfig().getLong("kk.defaultNoImageId");
				Long defaultYesImageId = ValueUtils.getConfig().getLong("kk.defaultYesImageId");

				String imageSql = "SELECT c1.FILE_URL deyes,c2.FILE_URL deno FROM FORMMAIN_0138"
						+ " LEFT JOIN CTP_ATTACHMENT c1 ON FORMMAIN_0138.FIELD0002 = c1.SUB_REFERENCE"
						+ " LEFT JOIN CTP_ATTACHMENT c2 ON FORMMAIN_0138.FIELD0005 = c2.SUB_REFERENCE"
						+ " WHERE FIELD0001=?";
				List<Map<String, Object>> ImgId = this.jdbcTemplate.queryForList(imageSql, affair.getMemberId());
				if (ImgId.size() > 0) {
					Map<String, Object> temp = ImgId.get(0);
					defaultYesImageId = MapUtils.getLong(temp, "deyes");
					defaultNoImageId = MapUtils.getLong(temp, "deno");
				}
				V3XFile defaultNoImageFile = this.fileManager.getV3XFile(defaultNoImageId);
				V3XFile defaultYesImageFile = this.fileManager.getV3XFile(defaultYesImageId);

				V3XFile vfile = defaultYesImageFile;
				List<Map<String, Object>> affairCommentVl = this.jdbcTemplate
						.queryForList("select * from ctp_comment_all where affair_id=?", affair.getId());
				V3xOrgMember aMember = this.orgManager.getMemberById(affair.getMemberId());

				String commentString = "";
				boolean dealAttitude = true;
				for (Iterator<Map<String, Object>> iterator = affairCommentVl.iterator(); iterator.hasNext();) {
					Map<String, Object> map = iterator.next();
					Date _cdate = (Date) map.get("create_date");
					commentString = DateFormatUtils.format(_cdate, "yyyy-MM-dd");
					dealAttitude = !"collaboration.dealAttitude.disagree".equals(MapUtils.getString(map, "ext_att1"));
					vfile = dealAttitude ? defaultYesImageFile : defaultNoImageFile;
				}

				for (int i = 1; i <= 10; i++) {
					if (needSave) {
						// 有一个意见匹配需要更新
						break;
					}
					FormFieldBean spFfb = formMasterBean.getFormTable().getFieldBeanByDisplay("审批" + i);
					if (spFfb == null) {
						continue;
					}
					Long memberId = MapUtils.getLong(formdata, spFfb.getName());

					if (affair.getMemberId().equals(memberId)) {
						// 赋值意见和态度
						// CAP4FormKitUtils.setCellValue(formMasterBean, "审批-意见"
						// +
						// i, commentString);
						CAP4FormKitUtils.setCellValue(formMasterBean, "审批" + i + "-日期", commentString);
						CAP4FormKitUtils.setCellValue(formMasterBean, "审批" + i + "-职位", aMember.getOrgPostId());
						needSave = true;
						FormFieldBean spImagefb = formMasterBean.getFormTable().getFieldBeanByDisplay("审批" + i + "-签名");
						Long attReferenceid = MapUtils.getLong(formdata, spImagefb.getName());
						if (attReferenceid != null) {
							// this.attachmentDAO.deleteByReference(attReferenceid);
						}
						long subReference = UUIDLong.longUUID();
						Attachment att = new Attachment(vfile, ApplicationCategoryEnum.collaboration,
								ATTACHMENT_TYPE.IMAGE);
						att.setReference(event.getSummaryId());
						att.setSubReference(subReference);
						att.setIdIfNew();
						att.setCategory(66);
						this.attachmentDAO.save(att);
						CAP4FormKitUtils.setCellValue(formMasterBean, "审批" + i + "-签名", subReference);
						System.out.println("stop添加签章：" + vfile);
						System.out.println("stop添加签章att：" + att);
					}

				}
				if (needSave) {
					this.formApi4Cap4.saveOrUpdateFormData(formMasterBean, formBean.getId(), true);
				}
			}
		} catch (Exception e) {
			log.info("MemberTongListtener is error 结束监听:", e);
		}
	}

	//@ListenEvent(event = CollaborationProcessEvent.class, async = true)
	public void onProcess(CollaborationProcessEvent event) {
		try {
			Thread.sleep(BaseListener.LISTENER_THREAD_SLEEPTIME);
			log.info("kk:处理监听：开始添加签章！start");
			String templetSubject = ValueUtils.getConfig().getString("kk.MemberShenPiFenPeiListtener");
			String[] templetSubjects = StringUtils.split(templetSubject, ",");
			ColSummary summary = this.colManager.getColSummaryById(event.getSummaryId()); // 获取协同信息
			CtpTemplate template = this.templateManager.getCtpTemplate(summary.getTempleteId());
			FormBean formBean = this.formManager.getFormByFormCode(template);
			if (ArrayUtils.contains(templetSubjects, template.getTempleteNumber())) {
				FormDataMasterBean formMasterBean = this.formManager.getDataMasterBeanById(summary.getFormRecordid(),
						formBean, null);
				Map<String, Object> formdata = formMasterBean.getAllDataMap();
			
				// 抄送人
				FormFieldBean csTFfb = formMasterBean.getFormTable().getFieldBeanByDisplay("抄送-填写");
				if (csTFfb != null) {
					String csTMembers = MapUtils.getString(formdata, csTFfb.getName());
					FormFieldBean csXFfb = formMasterBean.getFormTable().getFieldBeanByDisplay("抄送-显示");
					if (csTMembers != null) {
						String csXMembers = MapUtils.getString(formdata, csXFfb.getName()) + "," + csTMembers;
						CAP4FormKitUtils.setCellValue(formMasterBean, "抄送-显示", csXMembers);
						CAP4FormKitUtils.setCellValue(formMasterBean, "抄送-填写", null);
					}
				}
				CAP4FormKitUtils.setCellValue(formMasterBean, "抄送-填写", null);
				// 各个节点可以更换审批人或协议人 start
				List<String> sp = Lists.newArrayList();
				for (int i = 1; i <= 9; i++) {
					FormFieldBean spFfb = formMasterBean.getFormTable().getFieldBeanByDisplay("审批" + i);
					String member = MapUtils.getString(formdata, spFfb.getName());
					if (StringUtils.isNotEmpty(member)) {
						sp.add(member);
						V3xOrgMember aMember = this.orgManager.getMemberById(Long.parseLong(member));
						CAP4FormKitUtils.setCellValue(formMasterBean, "审批" + i + "-职位", aMember.getOrgPostId());
					} else
						CAP4FormKitUtils.setCellValue(formMasterBean, "审批" + i + "-职位", null);
				}
				// 第1到4的审批控件 是审批类型
				for (int i = 1; i <= 9; i++) {
					String mv = "";
					if (sp.size() >= i) {
						mv = sp.get(i - 1);
					}
					String fieldDisplayName = "审批" + i + "-姓名";
					CAP4FormKitUtils.setCellValue(formMasterBean, fieldDisplayName, mv);
				}

				CtpAffair affair = event.getAffair();
				Boolean needSave = false;

				// 这里需要根据用户 获取到个性化的签名，如果没有 则使用默认的
				Long defaultNoImageId = ValueUtils.getConfig().getLong("kk.defaultNoImageId");

				Long defaultYesImageId = ValueUtils.getConfig().getLong("kk.defaultYesImageId");

				String imageSql = "SELECT c1.FILE_URL deyes,c2.FILE_URL deno FROM FORMMAIN_0138"
						+ " LEFT JOIN CTP_ATTACHMENT c1 ON FORMMAIN_0138.FIELD0002 = c1.SUB_REFERENCE"
						+ " LEFT JOIN CTP_ATTACHMENT c2 ON FORMMAIN_0138.FIELD0005 = c2.SUB_REFERENCE"
						+ " WHERE FIELD0001=?";
				List<Map<String, Object>> ImgId = this.jdbcTemplate.queryForList(imageSql, affair.getMemberId());
				if (ImgId.size() > 0) {
					Map<String, Object> temp = ImgId.get(0);
					defaultYesImageId = MapUtils.getLong(temp, "deyes");
					defaultNoImageId = MapUtils.getLong(temp, "deno");
				}
				V3XFile defaultNoImageFile = this.fileManager.getV3XFile(defaultNoImageId);
				V3XFile defaultYesImageFile = this.fileManager.getV3XFile(defaultYesImageId);

				V3XFile vfile = defaultYesImageFile;
				List<Map<String, Object>> affairCommentVl = this.jdbcTemplate
						.queryForList("select * from ctp_comment_all where affair_id=?", affair.getId());
				String commentString = "";
				boolean dealAttitude = true;
				for (Iterator<Map<String, Object>> iterator = affairCommentVl.iterator(); iterator.hasNext();) {
					Map<String, Object> map = iterator.next();
					Date _cdate = (Date) map.get("create_date");
					commentString = DateFormatUtils.format(_cdate, "yyyy-MM-dd");
					dealAttitude = !"collaboration.dealAttitude.disagree".equals(MapUtils.getString(map, "ext_att1"));
					vfile = dealAttitude ? defaultYesImageFile : defaultNoImageFile;
				}
				V3xOrgMember aMember = this.orgManager.getMemberById(affair.getMemberId());

				for (int i = 1; i <= 10; i++) {
					if (needSave) {
						// 有一个意见匹配需要更新
						break;
					}
					FormFieldBean spFfb = formMasterBean.getFormTable().getFieldBeanByDisplay("审批" + i + "-姓名");
					if (spFfb == null) {
						continue;
					}

					Long memberId = MapUtils.getLong(formdata, spFfb.getName());

					if (affair.getMemberId().equals(memberId)) {
						// 赋值意见和态度
						// CAP4FormKitUtils.setCellValue(formMasterBean, "审批-意见"
						// +
						// i, commentString);
						CAP4FormKitUtils.setCellValue(formMasterBean, "审批" + i + "-日期", commentString);
						CAP4FormKitUtils.setCellValue(formMasterBean, "审批" + i + "-职位", aMember.getOrgPostId());
						needSave = true;
						FormFieldBean spImagefb = formMasterBean.getFormTable().getFieldBeanByDisplay("审批" + i + "-签名");
						Long attReferenceid = MapUtils.getLong(formdata, spImagefb.getName());
						if (attReferenceid != null) {
							// this.attachmentDAO.deleteByReference(attReferenceid);
						}
						long subReference = UUIDLong.longUUID();
						Attachment att = new Attachment(vfile, ApplicationCategoryEnum.collaboration,
								ATTACHMENT_TYPE.IMAGE);
						att.setReference(event.getSummaryId());
						att.setSubReference(subReference);
						att.setIdIfNew();
						att.setCategory(66);
						this.attachmentDAO.save(att);
						CAP4FormKitUtils.setCellValue(formMasterBean, "审批" + i + "-签名", subReference);
						CAP4FormKitUtils.setCellValue(formMasterBean, "抄送-填写", null);
						System.out.println("onProcess添加签章tong：" + vfile);
					}
				}
				if (needSave) {
					this.formApi4Cap4.saveOrUpdateFormData(formMasterBean, formBean.getId(), true);
					log.info("kk:处理监听：开始添加签章！end");
				}
			}
		} catch (Exception e) {
			log.info("MemberTongListtener is error 处理监听:", e);
		}
	}

}
